package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;

    /**
     * 查询套餐内的菜品
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public R<List<DishDto>> dishList(@PathVariable Long id) {
        //设置条件
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(id != null, SetmealDish::getSetmealId, id)
                .orderByDesc(SetmealDish::getUpdateTime);
        //在套餐菜品表中通过套餐id找到套餐下的所有菜品
        List<SetmealDish> setmealDishes = setmealDishService.list(wrapper);
        //套餐菜品表中没有菜品图片，进行以下转换
        List<DishDto> dishDtoList = setmealDishes.stream().map(setmealDish -> {
            //通过菜品id获取菜品信息
            Dish dish = dishService.getById(setmealDish.getDishId());
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            //在菜品dishDto对象中设置当前套餐中菜品的份数
            dishDto.setCopies(setmealDish.getCopies());
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtoList);
    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true) //清除setmealCache名称下,所有的缓存数据
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("ids:{}", ids);
        // 删除套餐的同时,需要将关联的菜品删除
        setmealService.removeWithDish(ids);
        return R.success("套餐数据删除成功");
    }

    /**
     * 分页查询套餐信息
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {

        Page<Setmeal> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!=null,Setmeal::getName,name);

        setmealService.page(pageInfo, wrapper);
        //=================转存并封装数据
        Page<SetmealDto> setmealDtoPageInfo = new Page<>();
        BeanUtils.copyProperties(pageInfo, setmealDtoPageInfo, "records");

        List<SetmealDto> setmealDtoList = pageInfo.getRecords().stream().map(item -> {
            Category category = categoryService.getById(item.getCategoryId());
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            setmealDto.setCategoryName(category.getName());
            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPageInfo.setRecords(setmealDtoList);
        return R.success(setmealDtoPageInfo);
    }

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true) //清除setmealCache名称下,所有的缓存数据
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("套餐信息：{}", setmealDto);

        setmealService.saveWithDish(setmealDto);

        return R.success("新增套餐成功");
    }


    /**
     * 根据条件查询套餐数据
     *
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }


    /**
     * 修改套餐
     *
     * @param
     * @return
     */


    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        log.info(setmealDto.toString());
        setmealService.updateWithDish(setmealDto);
        return R.success("修改套餐成功");
    }

    /**
     * 根据id查询套餐信息: 回显被修改的菜品数据
     *
     * @param id
     * @return
     */

    @GetMapping("/{id}")
    public R<SetmealDto> get(@PathVariable Long id) {
        SetmealDto SetmealDto = setmealService.getByIdWithDish(id);
        return R.success(SetmealDto);
    }

    /*
     * 套餐批量启用停用
     * */
    @PostMapping("/status/{status}")
    public R<String> stop(@PathVariable Integer status,@RequestParam List<Long> ids) {
        if (status == 0) {
            LambdaUpdateWrapper<Setmeal> wrapper = new LambdaUpdateWrapper<>();
            wrapper.in(Setmeal::getId, ids)
                    .set(Setmeal::getStatus, status);
            setmealService.update(wrapper);
        } else {
            //套餐内菜品是否停售
            LambdaQueryWrapper<SetmealDish> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.in(SetmealDish::getSetmealId, ids);
            List<SetmealDish> list = setmealDishService.list(wrapper1);
            list.stream().map((item)->{
                Dish byId = dishService.getById(item.getDishId());
                if (byId.getStatus()==0) {
                    throw new CustomException("套餐内有菜品停售，不能启售套餐");
                }
                return item;
            }).collect(Collectors.toList());


            LambdaUpdateWrapper<Setmeal> wrapper = new LambdaUpdateWrapper<>();
            wrapper.in(Setmeal::getId, ids)
                    .set(Setmeal::getStatus, status);
            setmealService.update(wrapper);

        }
        return R.success("操作成功");
    }
}